
import moment from 'moment'

class CacheObject {
    /**
     *Creates an instance of CacheObject.
     * @param {Object} data
     * @param {Date} expires
     * @memberof CacheObject
     */
    constructor(data, expires) {
        this.data = data;
        this.expires = expires;
    }
}

const cacheKeyPrefix = 'MyTampermonkeyCacheKey_';

export default class CacheHelper {

    /**
     * 取缓存
     *
     * @static
     * @param {string} key 缓存key
     * @returns cacheData || null
     * @memberof CacheHelper
     */
    static get(key) {
        if (!key) {
            return false;
        }
        const cacheObj = JSON.parse(localStorage.getItem(`${cacheKeyPrefix}${key}`));
        if (!cacheObj || cacheObj.expires > Date.now()) {
            return null
        }
        return cacheObj.data;
    }

    /**
     * 设置缓存
     *
     * @static
     * @param {string} key 缓存key
     * @param {object} data 缓存值
     * @param {number} [cacheMinute=60 * 24 * 365] 缓存时间，默认1年
     * @returns true || false
     * @memberof CacheHelper
     */
    static set(key, data, cacheMinute = 60 * 24 * 365) {
        if (!key) {
            return false;
        }
        if (!data) {
            return false;
        }
        if (cacheMinute < 0) {
            return false;
        }
        const cacheObj = new CacheObject(data, moment().add(cacheMinute, 'm').toDate());
        localStorage.setItem(`${cacheKeyPrefix}${key}`, JSON.stringify(cacheObj));
        return true;
    }

    /**
     * 删除缓存
     *
     * @static
     * @param {string} key 缓存key
     * @returns true || false
     * @memberof CacheHelper
     */
    static del(key) {
        if (!key) {
            return false;
        }
        localStorage.removeItem(`${cacheKeyPrefix}${key}`);
        return true;
    }

    /**
     * 清空缓存
     *
     * @static
     * @memberof CacheHelper
     */
    static clear() {
        Object.keys(localStorage).forEach((key) => {
            if (key.startsWith(cacheKeyPrefix)) {
                localStorage.removeItem(key);
            }
        });
    }
}